// 数据存储服务 - 开发者：彭鸿润
// 管理待办事项的数据存储和操作

import { reactive } from 'vue';

export const useTodoStore = () => {
  const data = reactive({
    todo: [],
    completed: []
  });

  // 从localStorage加载数据
  const loadData = () => {
    const stored = localStorage.getItem('todoList');
    if (stored) {
      const parsed = JSON.parse(stored);
      data.todo = parsed.todo || [];
      data.completed = parsed.completed || [];
    }
  };

  // 保存数据到localStorage
  const saveData = () => {
    localStorage.setItem('todoList', JSON.stringify(data));
  };

  // 添加待办事项
  const addTodo = (text) => {
    if (text.trim()) {
      data.todo.unshift(text.trim());
      saveData();
    }
  };

  // 删除待办事项
  const removeTodo = (index, isCompleted = false) => {
    if (isCompleted) {
      data.completed.splice(index, 1);
    } else {
      data.todo.splice(index, 1);
    }
    saveData();
  };

  // 完成/取消完成待办事项
  const toggleComplete = (index, isCompleted = false) => {
    if (isCompleted) {
      const item = data.completed.splice(index, 1)[0];
      data.todo.unshift(item);
    } else {
      const item = data.todo.splice(index, 1)[0];
      data.completed.unshift(item);
    }
    saveData();
  };

  return {
    data,
    loadData,
    saveData,
    addTodo,
    removeTodo,
    toggleComplete
  };
};
